package com.bosssoft.g1.authserver.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bosssoft.g1.authserver.api.CommonResult;
import com.bosssoft.g1.authserver.component.ContextHolder;
import com.bosssoft.g1.authserver.domain.Oauth2TokenDto;
import com.bosssoft.g1.authserver.service.UserServiceImpl;
import com.bosssoft.g1.authserver.vo.UserLoginVO;
import com.bosssoft.g1.common.data.vo.CommonResponse;
import com.bosssoft.g1.common.util.CommonResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.net.ContentHandler;
import java.security.Principal;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 * Created by macro on 2020/7/17.
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private ContextHolder contextHolder;

    @Autowired
    private UserServiceImpl userService;

    /**
     * Oauth2登录认证
     */
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public CommonResult<UserLoginVO> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        String username = parameters.get("username");
        String password = parameters.get("password");
        String account = parameters.get("account");
        if (ObjectUtil.isNull(username) || ObjectUtil.isNull(password) || ObjectUtil.isNull(account)) {
            return CommonResult.failed("请完整填写信息");
        }

        UserLoginVO check = userService.check(username, password, account);
        if (ObjectUtil.isNull(check)) {
            return CommonResult.failed("信息填写错误");
        }

        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead("Bearer ").build();

        BeanUtil.copyProperties(oauth2TokenDto, check);
        // 增加token到环境
        contextHolder.removeUserCode(username);
        contextHolder.setUserCode(username, oauth2TokenDto.getToken());

        return CommonResult.success(check);
    }

    /**
     * Oauth2登录认证
     */
    @GetMapping(value = "/checkToken")
    public CommonResponse<Boolean> checkToken(@NotNull @RequestParam("token") String token) throws HttpRequestMethodNotSupportedException {
        boolean result = true;
        if (StrUtil.isEmpty(token)) {
            result = false;
        }
        System.out.println(token);
        contextHolder.printAllKeysAndValues();

        result = contextHolder.hasValue(token);
        return CommonResponseUtils.booleanResult(result);
    }
}
